﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using BusinessObjects.BO_GetObjects;
using System.IO;
using DigiLib;
using System.Web.UI;

/// <summary>
/// Summary description for Pages_Base
/// </summary>
public class Admin_Controls_Base : System.Web.UI.UserControl {
    //Field
    protected int temp { get; set; }
    protected string keyword;
    protected string Keyword {
        get { return this.getRequest("keyword", string.Empty); }
    }
    protected int category_id;
    protected int Category_ID {
        get { return this.getRequest("category_id", 0); }
    }
    protected int Id {
        get { return this.getRequest("id", 0); }
    }
    protected int module_id;
    protected int Module_ID {
        get { return this.getRequest("module_id", 0); }
    }
    protected DataTable ObjDT { get; set; }
    protected int Page_size { get; set; }
    protected int Size_pager { get; set; }
    protected int cur_page = 0;
    protected int Cur_page(HtmlGenericControl pager) {
        string req = pager.ClientID;
        if (Request[req] != null)
            cur_page = Convert.ToInt32(Request[req]);
        if (cur_page == 0)
            cur_page = 1;
        return cur_page; ;
    }
    public Admin_Controls_Base() {
        Page_size = 15;
        Size_pager = 10;
    }
    //Gridview
    protected bool bindGridView(GridView grv, DataTable objDT, HtmlGenericControl messages) {
        try {
            if (objDT != null && objDT.Rows.Count > 0) {
                grv.Visible = true;
                grv.DataSource = objDT;
                grv.DataBind();
                return true;
            } else {
                grv.Visible = false;
                grv.DataSource = null;
                grv.DataBind();
                messages.InnerHtml = MessageBox.Warning("Cảnh Báo", "Chưa Có dữ liệu trong mục này!");
                return false;
            }
        } catch (Exception ex) {
            return false;
            throw ex;
        }
    }
    //Repeater
    protected bool bindRepeater(Repeater rpt, DataTable objDT) {
        try {
            if (objDT != null && objDT.Rows.Count > 0) {
                rpt.Visible = true;
                rpt.DataSource = objDT;
                rpt.DataBind();
                return true;
            } else {
                rpt.Visible = false;
                rpt.DataSource = null;
                rpt.DataBind();
                return false;
            }
        } catch (Exception ex) {
            return false;
            throw ex;
        }
    }
    protected bool bindRepeater(Repeater rpt, DataTable objDT, HtmlGenericControl messages) {
        try {
            if (objDT != null && objDT.Rows.Count > 0) {
                rpt.Visible = true;
                rpt.DataSource = objDT;
                rpt.DataBind();
                return true;
            } else {
                rpt.Visible = false;
                rpt.DataSource = null;
                rpt.DataBind();
                messages.InnerHtml = MessageBox.Warning("Cảnh Báo", "Chưa Có dữ liệu trong mục này!");
                return false;
            }
        } catch (Exception ex) {
            throw ex;
        }
    }
    protected bool bindRepeater(Repeater rpt, DataTable objDT, HtmlGenericControl messages, HtmlGenericControl pager) {
        try {
            if (objDT != null && objDT.Rows.Count > 0) {
                /////////           Pager       //////////                                
                string url = Request.Url.ToString();

                if (url.IndexOf("&" + pager.ClientID) > 0) {
                    string temp1, temp2;
                    temp1 = url.Remove(url.IndexOf("&" + pager.ClientID));
                    temp2 = url.Replace(temp1, "");
                    int index = temp2.IndexOf("&", 1);
                    if (index > 0)
                        temp2 = temp2.Substring(index, temp2.Length - index);
                    else
                        temp2 = "";
                    url = temp1 + temp2;
                }
                url += "&" + pager.ClientID + "=$CUR_PAGE";
                pager.InnerHtml = DigiPager.CmsPaging(Page_size, Size_pager, Cur_page(pager), Convert.ToInt32(objDT.Rows[0]["TOTAL_ROWS"]), url);
                pager.Visible = true;
                /////////           End Pager       ////////                                
                rpt.DataSource = objDT;
                rpt.DataBind();
                rpt.Visible = true;
                return true;
            } else {
                rpt.Visible = false;
                pager.InnerHtml = string.Empty;
                pager.Visible = false;
                rpt.DataSource = null;
                rpt.DataBind();
                messages.InnerHtml = MessageBox.Warning("Cảnh Báo", "Chưa Có dữ liệu trong mục này!");
                return false;
            }
        } catch (Exception ex) {
            throw ex;
        }
    }
    protected bool bindRepeater(Repeater rpt, DataTable objDT, HtmlGenericControl messages, HtmlGenericControl pager, string errorMessage) {
        try {
            if (objDT != null && objDT.Rows.Count > 0) {
                /////////           Pager       //////////                                
                string url = Request.Url.ToString();
                if (url.IndexOf("&" + pager.ClientID) > 0) {
                    string temp1, temp2;
                    temp1 = url.Remove(url.IndexOf("&" + pager.ClientID));
                    temp2 = url.Replace(temp1, "");
                    int index = temp2.IndexOf("&", 1);
                    if (index > 0)
                        temp2 = temp2.Substring(index, temp2.Length - index);
                    else
                        temp2 = "";
                    url = temp1 + temp2;
                }
                url += "&" + pager.ClientID + "=$CUR_PAGE";
                pager.InnerHtml = DigiPager.CmsPaging(Page_size, Size_pager, Cur_page(pager), Convert.ToInt32(objDT.Rows[0]["TOTAL_ROWS"]), url);
                pager.Visible = true;
                /////////           End Pager       ////////                                
                rpt.DataSource = objDT;
                rpt.DataBind();
                rpt.Visible = true;
                return true;
            } else {
                rpt.Visible = false;
                pager.InnerHtml = string.Empty;
                pager.Visible = false;
                rpt.DataSource = null;
                rpt.DataBind();
                messages.InnerHtml = MessageBox.Warning("Cảnh Báo", errorMessage);
                return false;
            }
        } catch (Exception ex) {
            throw ex;
        }
    }
    //Request
    protected string removeRequest(string[] request) {
        string url = Request.Url.ToString();
        int conti;
        foreach (string per in request) {
            if (Request[per] != null) {
                conti = url.LastIndexOf(per + "=");
                string start = url.Substring(0, url.LastIndexOf("&" + per + "="));
                string end = url.Substring(conti, url.Length - conti);
                conti = end.IndexOf("&");
                if (conti > -1)
                    url = start + end.Substring(conti, end.Length - conti);
                else
                    url = start;
            }

        }
        return url;
    }
    protected string removeRequest(string url, string request) {
        int conti;
        if (Request[request] != null) {
            conti = url.LastIndexOf(request + "=");
            string start = url.Substring(0, url.LastIndexOf("&" + request + "="));
            string end = url.Substring(conti, url.Length - conti);
            conti = end.IndexOf("&");
            if (conti > -1)
                url = start + end.Substring(conti, end.Length - conti);
            else
                url = start;
        }
        return url;
    }
    protected string getRequest(string req, string nullval) {
        string val;
        if (Request[req] != null)
            val = Request[req].ToString();
        else
            val = nullval;
        return val;
    }
    protected int getRequest(string req, int nullval) {
        int val;
        if (Request[req] != null)
            val = Convert.ToInt32(Request[req]);
        else
            val = nullval;
        return val;
    }
    //DropDownList
    protected void bindDDL(DropDownList ddl, DataTable objDT, string text, string value) {
        if (objDT != null && objDT.Rows.Count > 0) {
            ddl.DataSource = objDT;
            ddl.DataTextField = text;
            ddl.DataValueField = value;
            ddl.DataBind();
        }
    }
    protected void bindDDL(DropDownList ddl, DataTable objDT, string[] attrs, string[] fields) {
        if (objDT != null && objDT.Rows.Count > 0) {
            ListItem item;
            foreach (DataRow row in objDT.Rows) {
                item = new ListItem(row["FULL_CATEGORY_NAME"].ToString(), row["CATEGORY_ID"].ToString());
                for (int i = 0; i < attrs.Length; i++)
                    item.Attributes.Add(attrs[i], row[fields[i]].ToString());
                ddl.Items.Add(item);
            }
        }
    }
    protected void bindDDL(DropDownList ddl, DataTable objDT, string text, string value, string nullText, string nullValue) {
        if (objDT != null && objDT.Rows.Count > 0) {
            ddl.DataSource = objDT;
            ddl.DataTextField = text;
            ddl.DataValueField = value;
            ddl.DataBind();
        } else
            if (ddl.Items.Count == 0)
                ddl.Items.Add(new ListItem(nullText, nullValue));
    }
    //ListBox
    protected void bindLSB(ListBox lsb, DataTable objDT, string text, string value) {
        if (objDT != null && objDT.Rows.Count > 0) {
            lsb.DataSource = objDT;
            lsb.DataTextField = text;
            lsb.DataValueField = value;
            lsb.DataBind();
        }
    }
    //CheckbockList
    protected void bindCBL(CheckBoxList cbl, DataTable objDT, string text, string value) {
        if (objDT != null && objDT.Rows.Count > 0) {
            cbl.DataSource = objDT;
            cbl.DataTextField = text;
            cbl.DataValueField = value;
            cbl.DataBind();
        } else
            cbl.Visible = false;
    }
    //Module        
    protected void removeHGC(HtmlGenericControl htmlgenericcontrol) {
        if (htmlgenericcontrol.InnerHtml != String.Empty)
            htmlgenericcontrol.InnerHtml = String.Empty;
    }
    //Fileupload    
    protected string Upload(string folder, string fileName, FileUpload ful, HtmlGenericControl message, string basefolder) {
        if (ful.HasFile) {
            try {
                string BaseFolder = "administrator/uploaded/";
                string FolderYear;
                string FolderMonth;
                string FolderDay;
                if (fileName.Equals(string.Empty)) {
                    DateTime now = DateTime.Now;
                    FolderYear = now.Year.ToString();
                    FolderMonth = now.Month.ToString();
                    FolderDay = now.Day.ToString();
                } else {
                    string[] dir = fileName.Split('/');
                    FolderYear = dir[4];
                    FolderMonth = dir[5];
                    FolderDay = dir[6];
                }
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay));
                fileName = ful.FileName;
                int count = 0;
                while (File.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName))) {
                    fileName = count + "_" + ful.FileName;
                    count++;
                }
                ful.SaveAs(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName));
                return "/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName;
            } catch (Exception ex) {
                message.InnerHtml = MessageBox.Error("Hệ Thống", "Lỗi ghi file! " + ex.Message);
                return fileName;
            }
        } else
            return fileName;
    }
    protected string Upload(string folder, string fileName, FileUpload ful, HtmlGenericControl message, bool admin) {
        if (ful.HasFile) {
            try {
                string BaseFolder; int spe; string FolderYear; string FolderMonth; string FolderDay;
                if (admin) { BaseFolder = Setting.PathAdmin; spe = 3; } else { BaseFolder = Setting.Path; spe = 2; }
                if (fileName.Equals(string.Empty)) {
                    DateTime now = DateTime.Now;
                    FolderYear = now.Year.ToString();
                    FolderMonth = now.Month.ToString();
                    FolderDay = now.Day.ToString();
                } else {
                    string[] dir = fileName.Split('/');
                    FolderYear = dir[spe];
                    FolderMonth = dir[spe + 1];
                    FolderDay = dir[spe + 2];
                }
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay));
                fileName = ful.FileName;
                int count = 0;
                while (File.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName))) {
                    fileName = count + "_" + ful.FileName;
                    count++;
                }
                ful.SaveAs(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName));
                return folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName;
            } catch (Exception ex) {
                message.InnerHtml = MessageBox.Error("Hệ Thống", "Lỗi ghi file! " + ex.Message);
                return fileName;
            }
        } else
            return fileName;
    }
    protected string Upload(string folder, string fileName, HttpPostedFile hpf, HtmlGenericControl message) {
        if (hpf.ContentLength > 0) {
            try {
                string BaseFolder = "administrator/uploaded/";
                string FolderYear;
                string FolderMonth;
                string FolderDay;
                if (fileName.Equals(string.Empty)) {
                    DateTime now = DateTime.Now;
                    FolderYear = now.Year.ToString();
                    FolderMonth = now.Month.ToString();
                    FolderDay = now.Day.ToString();
                } else {
                    string[] dir = fileName.Split('/');
                    FolderYear = dir[1];
                    FolderMonth = dir[2];
                    FolderDay = dir[3];
                }
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth));
                if (!Directory.Exists(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay)))
                    Directory.CreateDirectory(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay));
                fileName = System.IO.Path.GetFileName(hpf.FileName);
                hpf.SaveAs(Server.MapPath("~/" + BaseFolder + folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName));
                return folder + "/" + FolderYear + "/" + FolderMonth + "/" + FolderDay + "/" + fileName;
            } catch (Exception ex) {
                message.InnerHtml = MessageBox.Error("Hệ Thống", "Lỗi ghi file! " + ex.Message);
                throw ex;
            }
        } else
            return fileName;
    }
    protected void search(string keyword) {
        if (keyword != null && !keyword.Equals("") && !keyword.Equals("Hãy nhập từ khóa !")) {
        }
    }
    protected void Clear(ControlCollection controls) {
        foreach (Control ctl in controls) {
            if (ctl is TextBox) ((TextBox)(ctl)).Text = string.Empty;
            else if (ctl is DropDownList) ((DropDownList)(ctl)).SelectedIndex = 0;
            else if (ctl is ListBox) ((ListBox)(ctl)).SelectedIndex = 0;
            else if (ctl is CheckBox) ((CheckBox)(ctl)).Checked = false;
        }
    }

    //---------------------------------Can-Error---------------------
    protected void ModuleByContent(DropDownList ddl, string content_type, int option) {
        ObjDT = BO_portal_modules.SelectContent(content_type, option);
        if (ObjDT != null && ObjDT.Rows.Count > 0)
            foreach (DataRow dr in ObjDT.Rows) {
                ListItem item = new ListItem(dr["FULL_NAME"].ToString(), dr["MODULE_ID"].ToString());
                ddl.Items.Add(item);
            }
    }
    protected void ModuleByContent(DropDownList ddl, string content_type, string classes, int option) {
        ObjDT = BO_portal_modules.SelectContent(content_type, option);
        if (ObjDT != null && ObjDT.Rows.Count > 0)
            foreach (DataRow dr in ObjDT.Rows) {
                ListItem item = new ListItem(dr["FULL_NAME"].ToString(), dr["MODULE_ID"].ToString());
                item.Attributes.Add("class", dr[classes].ToString());
                ddl.Items.Add(item);
            }
    }
    protected void ModuleByContent(ListBox lsb, string content_type, int option) {
        ObjDT = BO_portal_modules.SelectContent(content_type, option);
        if (ObjDT != null && ObjDT.Rows.Count > 0)
            foreach (DataRow dr in ObjDT.Rows) {
                ListItem item = new ListItem(dr["FULL_NAME"].ToString(), dr["MODULE_ID"].ToString());
                lsb.Items.Add(item);
            }
    }
    //Remove exception is parent    
    public string GetSelectedItems(Repeater rpt, string chkBoxId) {
        var selectedValues = string.Empty;
        for (int i = 0; i < rpt.Items.Count; i++) {
            var chkBox = rpt.Items[i].FindControl(chkBoxId) as HtmlInputCheckBox;
            if (chkBox != null && chkBox.Checked)
                selectedValues += chkBox.Value + ";";
        }
        return selectedValues;
    }
}